package com.xiongwei.manageback.interceptor;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.xiongwei.manageback.config.TokenConfig;
import com.xiongwei.manageback.domain.SysUser;
import com.xiongwei.manageback.exception.ServiceException;
import com.xiongwei.manageback.mapper.SysUserMapper;
import com.xiongwei.manageback.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private SysUserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
//        token是否为空
        if (StrUtil.isBlank(token)){
            throw new ServiceException(ServiceException.AUTH_NOT,"无token，请重新登录");
        }
//        token能否取出userId
        Integer userId;
        try{
            userId = Integer.valueOf(JWT.decode(token).getAudience().get(0));
        }catch (JWTDecodeException e){
            throw new ServiceException(ServiceException.AUTH_NOT,"token验证失败，请重新登录");
        }
//        能否查询出用户信息
        SysUser user;
        try {
            user = userService.getById(userId);
        } catch (Exception e) {
            throw new ServiceException(ServiceException.USER_NOT_FUND,"用户不存在");
        }
//        加签验证token
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ServiceException(ServiceException.AUTH_NOT,"token验证失败，请重新登录");
        }

        return true;
    }
}
